package com.restaurant.servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;

/**
 * Servlet implementation class CategoryImageDownloaderServlet
 */
@WebServlet("/CategoryImageDownloaderServlet")
public class CategoryImageDownloaderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CategoryImageDownloaderServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		download(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
	
	
	private void download(HttpServletRequest request, HttpServletResponse response)  {
		 
		File file = new File(request.getServletContext().getInitParameter("imagePath") + request.getParameter("image"));
		
		if(file.isDirectory()){
			file = null;
			file = new File(request.getServletContext().getInitParameter("projectImages") + "no-pic.gif" );
		}
		
		if(file.exists()){
			response.setContentType("image");
			response.setContentLength((int)file.length());
			response.setHeader("Content-Disposition","attachment; filename=\"" + request.getParameter("image")!=null ?  request.getParameter("image") : "no-pic.gif"  +"\"");
			 
			try {
				FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
	}

}
